package com.webcams.ui;

import java.util.ArrayList;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.view.Display;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.Surface;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

import com.webcams.core.exceptions.DataConnectionException;
import com.webcams.core.resorts.ResortsManager;
import com.webcams.ui.compass.CompassUI;
import com.webcams.ui.downloadmaps.DownloadMapsUI;
import com.webcams.ui.resorts.DepartementsUI;

public class IndexUI extends Activity {

	private MenuChoiceList menu;


	public Handler connectionErrorHandler;

	@Override
	public void onCreate(Bundle state) {
		super.onCreate(state);

		setContentView(R.layout.index);

		Resources resources = this.getResources();
		
		menu = new MenuChoiceList();
		menu.add(resources.getString(R.string.index_resorts), R.drawable.index_resort, DepartementsUI.class);
		menu.add(resources.getString(R.string.index_tracker), R.drawable.index_tracker, null);
		menu.add(resources.getString(R.string.index_compass), R.drawable.index_compass, CompassUI.class);
		menu.add(resources.getString(R.string.index_downloadmaps), R.drawable.index_maps, DownloadMapsUI.class);
		//menu.add(resources.getString(R.string.index_settings), R.drawable.index_settings, SettingsUI.class);
		menu.add(resources.getString(R.string.index_about), R.drawable.index_about, AboutUI.class);

		GridView grid = (GridView) findViewById(R.id.homeScreen);
		grid.setAdapter(new HomeScreenShortcutAdapter());
		grid.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View v, int position,
					long id) {
				launchActivity(position);
			}
		});


		connectionErrorHandler = new Handler();

		refreshConnection();
	}
	
	private void refreshConnection(){

		final ProgressDialog progressDialog = new ProgressDialog(this);
		progressDialog.setCancelable(false);
		progressDialog.setMessage(getResources().getString(R.string.index_loading));
		progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		progressDialog.show();
		
		new Thread(new Runnable(){
			@Override
			public void run() {
				try {
					ResortsManager.getInstance(IndexUI.this).download();
				} catch (DataConnectionException e) {
					connectionErrorHandler.post(new Runnable() {
						@Override
						public void run() {
							Toast.makeText(IndexUI.this, getResources().
									getString(R.string.index_error_internet_connection_message1), Toast.LENGTH_SHORT).show();
							Toast.makeText(IndexUI.this, getResources().
									getString(R.string.index_error_internet_connection_message2), Toast.LENGTH_SHORT).show();
						}
					});
				}
				ResortsManager.getInstance(IndexUI.this).load();
				progressDialog.dismiss();
			}
		}).start();
	}


	protected void launchActivity(int position) {
		if(menu.get(position).getIntentClass() != null) {
			Intent i = new Intent();
			i.setClass(this, menu.get(position).getIntentClass());
			startActivity(i);      
		} else {
			Toast.makeText(this, getResources().getString(R.string.index_not_implemented_yet), Toast.LENGTH_SHORT).show();
		}
	}

	@Override
	protected void onDestroy(){
		super.onDestroy();
	}


	public class HomeScreenShortcutAdapter extends BaseAdapter {

		public HomeScreenShortcutAdapter() {

		}

		@Override
		public int getCount() {
			return menu.size();
		}

		@Override
		public Object getItem(int position) {
			return menu.get(position);
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			TextView tv;
			final MenuChoice data = (MenuChoice) getItem(position);

			if (convertView == null) {

				tv = new TextView(getApplicationContext());
				tv.setGravity(Gravity.CENTER);

			} else {
				tv = (TextView) convertView;
			}

			Drawable icon = data.getIcon();
			CharSequence title = data.getName();

			tv.setCompoundDrawablesWithIntrinsicBounds(
					null, icon, null, null);
			tv.setText(title);
			tv.setTag(data);
			tv.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
			tv.setTextColor(Color.WHITE);

			return tv;
		}

	}

	public class MenuChoice {
		private String name;
		private Drawable icon;
		private Class<?> intentClass;

		public MenuChoice(String name, int iconId, Class<?> intentClass) {
			this.name = name;
			this.icon = getResources().getDrawable(iconId);
			this.intentClass = intentClass;
		}

		public Class<?> getIntentClass() {
			return intentClass;
		}

		public Drawable getIcon() {
			return icon;
		}

		public String getName() {
			return name;
		}

	}

	public class MenuChoiceList extends ArrayList<MenuChoice>{

		private static final long serialVersionUID = 1178042022949977077L;

		public void add(String choiceName, int iconId, Class<?> intentClass) {
			add(new MenuChoice(choiceName, iconId, intentClass));
		}
	}


	@Override
	public void onConfigurationChanged(Configuration newConfig) {	    

		Display display = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
		GridView grid = (GridView) findViewById(R.id.homeScreen);

		switch(display.getRotation()) {
		case Surface.ROTATION_90:
		case Surface.ROTATION_270:
		case Surface.ROTATION_180:
			grid.setNumColumns(3);
			break;
		case Surface.ROTATION_0:
			grid.setNumColumns(2);
			break;
		}

		super.onConfigurationChanged(newConfig);

	}
	
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_index, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.index_menu_refreshconnection:
    		refreshConnection();
        	return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }


}
